package cn.snmp.mutual.org.opennms.protocols.icmp;

import cn.snmp.mutual.org.opennms.protocols.exceptions.InsufficientDataException;
import cn.snmp.mutual.org.opennms.protocols.exceptions.OverflowDataException;
import cn.snmp.mutual.org.opennms.protocols.ip.IPHeader;


public class ErrorMessage extends ICMPHeader {
    private IPHeader m_iphdr;
    private byte[] m_protoData;

    protected ErrorMessage(final byte type, final byte code) {
        super(type, code);
        this.m_iphdr = null;
        this.m_protoData = null;
    }

    public ErrorMessage(final byte[] buf, final int offset) {
        this.loadFromBuffer(buf, offset);
    }

    public int loadFromBuffer(final byte[] buf, int offset) {
        if (buf.length < offset + 36) {
            throw new InsufficientDataException("Insufficient data to load ICMP error message");
        }
        offset = super.loadFromBuffer(buf, offset);
        this.m_iphdr = new IPHeader(buf, offset);
        if (buf.length < offset + 16 + this.m_iphdr.getHeaderLength()) {
            throw new InsufficientDataException("Insufficient data to load ICMP error message");
        }
        offset += this.m_iphdr.getHeaderLength();
        this.m_protoData = new byte[8];
        for (int x = 0; x < 8; ++x) {
            this.m_protoData[x] = buf[offset++];
        }
        return offset;
    }

    public IPHeader getIPHeader() {
        return this.m_iphdr;
    }

    protected void setIPHeader(final IPHeader hdr) {
        this.m_iphdr = hdr;
    }

    public byte[] getProtocolData() {
        return this.m_protoData;
    }

    protected void setProtocolData(final byte[] pd) {
        if (pd.length < 8) {
            throw new InsufficientDataException("Protocol data must be 8 bytes in length");
        }
        if (pd.length > 8) {
            throw new OverflowDataException("Protocol data cannot be more than 8 bytes in length");
        }
        this.m_protoData = pd;
    }
}
